import pysvn, sys
from time import localtime
from datetime import datetime
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.interfaces import PoolListener

from model import *

class SetTextFactory(PoolListener):
    def connect(self, dbapi_con, con_record):
        dbapi_con.text_factory = str
        
engine = create_engine('sqlite:///test.db', echo=False, listeners=[SetTextFactory()])

metadata = Base.metadata
metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

svn = pysvn.Client()

repo_url = 'http://digvcs.googlecode.com/svn/'
if len(sys.argv) > 1:
	repo_url = sys.argv.pop()

logs = svn.log(repo_url, discover_changed_paths=True, limit=0)

for log in logs:
    author = ""
    try:
        author = log['author']
    except KeyError:
        author = "unknown"
    rev = Revision( 
        author  = author,
        message = log['message'],
        date    = datetime(*localtime(log['date'])[:6]),
        rev_num = log['revision'].number            
    )
    session.add(rev)
    
    for cp in log['changed_paths']:
        session.add(
            Change(
                revision = rev,
                action   = cp['action'],
                path     = cp['path']
            )
        )
            
session.flush()
session.commit()
